/*
 * Copyright 2010 Kevin L'Huillier <klhuillier@gmail.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.lhuillier.pwsafe.model;


import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;


/**
 * Either indicates the lack of password history for the record or holds the
 * password history for the record.
 * <p>
 * This stores entries in the same order as Password Safe: oldest first
 */
public class PasswordHistory {
    private boolean enabled;
    private int maxSize;
    private LinkedList<PasswordHistoryEntry> entries;

    public PasswordHistory(boolean enabled, int maxSize,
            ArrayList<PasswordHistoryEntry> entries) {
        this.enabled = enabled;
        this.maxSize = maxSize;
        this.entries = entries == null ? new LinkedList<PasswordHistoryEntry>()
                : new LinkedList<PasswordHistoryEntry>(entries);
    }

    public void addEntry(PasswordHistoryEntry entry) {
        entries.addLast(entry);
        prune();
    }

    public void setMaxSize(int maxSize) {
        this.maxSize = maxSize;
        prune();
    }

    public int getMaxSize() {
        return maxSize;
    }

    public int getCurrentSize() {
        return entries.size();
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public boolean isEnabled() {
        return enabled;
    }

    private void prune() {
        while (entries.size() > maxSize) {
            entries.removeFirst();
        }
    }

    /**
     * @return an unmodifiable List of the entries
     */
    public List<PasswordHistoryEntry> getEntries() {
        return Collections.unmodifiableList(entries);
    }

    @Override
    public String toString() {
        return getClass().getName() + "[enabled=" + enabled + ";maxSize="
                + maxSize + ";entries=" + entries.size() + "]";
    }
}
